package com.ly.aidlpratice.client

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ly.aidlpratice.bean.Book
import com.ly.aidlpratice.handwritten.ClientBookCallback
import com.ly.aidlpratice.handwritten.ClientBookProxy
import com.ly.aidlpratice.handwritten.IBookInterface
import com.ly.aidlpratice.util.logDebug
import com.ly.aidlpratice.util.logError
import java.lang.Exception

class HandwrittenActivity : AppCompatActivity() {

    private val mTag: String by lazy { this::class.java.simpleName }

    private lateinit var mIBookInterface: IBookInterface

    private lateinit var mBook: Book

    private var mService: IBinder? = null

    //当远程服务死亡时，会接到通知；可以做释放资源的处理
    private val mDeathRecipient = IBinder.DeathRecipient {
        logDebug(mTag, "remote binder died")
        mService = null
    }

    private val mServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            logDebug(mTag, "onServiceConnected[$name]")
            service?.also {
                mIBookInterface = ClientBookProxy(it)
                mService = it
                it.linkToDeath(mDeathRecipient, 0)
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            logDebug(mTag, "onServiceDisconnected[$name]")
        }

        override fun onBindingDied(name: ComponentName?) {
            super.onBindingDied(name)
            logDebug(mTag, "onBindingDied[$name]")
        }

        override fun onNullBinding(name: ComponentName?) {
            super.onNullBinding(name)
            logDebug(mTag, "onNullBinding[$name]")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handwritten)

        findViewById<Button>(R.id.button8).setOnClickListener {
            val intent = Intent()
            intent.component = ComponentName(
                "com.ly.aidlpratice",
                "com.ly.aidlpratice.handwritten.HandwrittenService"
            )
            val result = bindService(intent, mServiceConnection, Service.BIND_AUTO_CREATE)
            if (result) {
                showToast("绑定成功")
            }
        }

        findViewById<Button>(R.id.button9).setOnClickListener {
            try {
                unbindService(mServiceConnection)
                val flag = mService?.unlinkToDeath(mDeathRecipient, 0)
                showToast("服务解绑:$flag")
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //获取一本书
        findViewById<Button>(R.id.button10).setOnClickListener {
            try {
                if (isConnection()) {
                    mBook = mIBookInterface.getBook()
                    logDebug(mTag, "book:$mBook")
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //获取所有书
        findViewById<Button>(R.id.button11).setOnClickListener {
            try {
                if (isConnection()) {
                    val list = mIBookInterface.getAllBook()
                    if (list.isEmpty()) {
                        logDebug(mTag, "allBook is empty")
                    } else {
                        logDebug(mTag, "allBook begin")
                        for (book in list) {
                            logDebug(mTag, "book:$book")
                        }
                        logDebug(mTag, "allBook end")
                    }
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //更新某本书的价格
        findViewById<Button>(R.id.button12).setOnClickListener {
            try {
                if (isConnection()) {
                    if (this::mBook.isInitialized) {
                        mIBookInterface.updateBookPrice(mBook.code, 45.5f)
                    } else {
                        showToast("先获取一本书")
                    }
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //是否存在《西游记》
        findViewById<Button>(R.id.button13).setOnClickListener {
            try {
                if (isConnection()) {
                    ///远程服务中isContainBook方法进行了线程睡眠8s，所以在主线程调用该方法会出现掉帧
                    ///像这种场景应该在后台线程调用方法，如果必要，再把结果发给主线程
                    val result = mIBookInterface.isContainBook("西游记")
                    logDebug(mTag, "是否存在《西游记》：$result")
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //获取某本书的价格
        findViewById<Button>(R.id.button14).setOnClickListener {
            try {
                if (isConnection()) {
                    if (this::mBook.isInitialized) {
                        Thread {
                            val price = mIBookInterface.getBookPrice(mBook.code)
                            logDebug(mTag, "《${mBook.name}》的价格是$price")
                        }.start()
                    } else {
                        showToast("先获取一本书")
                    }
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //增加一本书
        findViewById<Button>(R.id.button15).setOnClickListener {
            try {
                if (isConnection()) {
                    mIBookInterface.insertBook(Book("水浒传", 4000, 34f))
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //增加多本书
        findViewById<Button>(R.id.button16).setOnClickListener {
            try {
                if (isConnection()) {
                    val list = ArrayList<Book>()
                    list.add(Book("Flutter从入门到精通", 4001, 40f))
                    list.add(Book("Kotlin从入门到精通", 4002, 45f))
                    list.add(Book("Java从入门到精通", 4003, 39.9f))
                    list.add(Book("Android从入门到精通", 4004, 49.9f))

                    mIBookInterface.insertBookList(list)
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //获取书的映射表
        findViewById<Button>(R.id.button17).setOnClickListener {
            try {
                if (isConnection()) {
                    val map = mIBookInterface.getBookMap()
                    logDebug(mTag, "bookMap start")
                    for ((index, book) in map) {
                        logDebug(mTag, "index:$index book:$book")
                    }
                    logDebug(mTag, "bookMap end")
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //插入书的映射表
        findViewById<Button>(R.id.button18).setOnClickListener {
            try {
                if (isConnection()) {
                    val map = HashMap<Int, Book>()
                    map[4001] = Book("Flutter从入门到精通", 4001, 40f)

                    mIBookInterface.insertBookMap(map)

                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        val callback = object : ClientBookCallback() {
            override fun callback(book: Book) {
                logDebug(mTag, "callback$book")
            }
        }

        //注册回调监听
        findViewById<Button>(R.id.button21).setOnClickListener {
            try {
                if (isConnection()) {
                    mIBookInterface.registerCallback(callback)
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }

        //注销回调监听
        findViewById<Button>(R.id.button22).setOnClickListener {
            try {
                if (isConnection()) {
                    mIBookInterface.unregisterCallback(callback)
                }
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }
    }

    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }

    private fun isConnection(): Boolean {
        val flag = this::mIBookInterface.isInitialized
        if (!flag) {
            showToast("远程服务还未连接")
        } else {
            logDebug(mTag, "RemoteBinder is ${mService?.pingBinder()}")
        }
        return flag
    }
}